# -*- coding: utf-8 -*-

import os
import logging
from logging.handlers import TimedRotatingFileHandler


class Logger:
    def __init__(self, app=None):
        self.app = app
        if app is not None:
            self.init_app(app)

    def init_app(self, app):
        # 对所有的targets设置统一的handler, formatter, level等配置
        #
        self.app = app

        app.config.setdefault('LOGGER_TARGETS', [])
        app.config.setdefault('LOGGER_LEVELS', ['INFO'])
        app.config.setdefault('LOGGER_ENCODING', 'utf-8')
        app.config.setdefault('LOGGER_FILE_PATH', os.path.join(app.base_path, 'log'))
        app.config.setdefault('LOGGER_FILE_PREFIX', 'gzone')
        app.config.setdefault(
            'LOGGER_FORMAT',
            '[%(levelname)s]-[%(name)s]-[%(funcName)s]-[%(asctime)s]: %(message)s'
        )

        logger_targets = [logging.getLogger(l) for l in app.config['LOGGER_TARGETS']]
        logger_targets.append(app.logger)

        log_encoding = app.config['LOGGER_ENCODING']
        log_path = app.config['LOGGER_FILE_PATH']
        log_prefix = app.config['LOGGER_FILE_PREFIX']
        log_format = app.config['LOGGER_FORMAT']
        log_levels = app.config['LOGGER_LEVELS']
        # log_levels = [
        #     getattr(logging, lvl.upper())
        #     for lvl in app.config['LOGGER_LEVELS']
        # ]
        # min_level = min(log_levels)
        formatter = logging.Formatter(log_format)

        # todo: need modification here
        for logger in logger_targets:
            if logger.level == logging.NOTSET:
                logger.setLevel(logging.DEBUG)

        handlers = []
        for lvl in log_levels:
            handler = TimedRotatingFileHandler(
                os.path.join(log_path, '{}-{}.log'.format(log_prefix, lvl.lower())),
                encoding=log_encoding,
                when='midnight'
            )
            # handler.setLevel(min_level)
            handler.setLevel(getattr(logging, lvl.upper()))
            handler.setFormatter(formatter)
            handlers.append(handler)

            for logger in logger_targets:
                logger.addHandler(handler)

        app.meng_logger = self
